package com.solairen.myapplication.Pager.HomePager;

import android.content.Intent;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.solairen.myapplication.R;
import com.solairen.myapplication.data.Item;
import com.solairen.myapplication.utils.UtilsKt;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ConsultationFragment extends Fragment {

    private SearchView searchView;
    private RecyclerView recyclerView;

    private MAdapter mAdapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 在这里设置 dashboard_fragment 的布局文件
        View view = inflater.inflate(R.layout.fragment_consultation, container, false);
        try {
            init(view);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return view;
    }

    private void init(View view) throws IOException {
        searchView = view.findViewById(R.id.searchView);
        recyclerView = view.findViewById(R.id.recyclerView);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        List<Item> items = createItem("");
        mAdapter = new MAdapter(items);
        recyclerView.setAdapter(mAdapter);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 在用户提交搜索查询时调用，处理搜索逻辑
                try {
                    performSearch(query);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.equals("")) {
                    try {
                        performSearch("");
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                return false;
            }
        });
    }

    private void performSearch(String query) throws IOException {
        // 处理搜索逻辑，例如从数据库或网络获取搜索结果，并更新 UI
        List<Item> item = createItem(query);
        mAdapter.updateData(item);
    }

    private List<Item> createItem(String searchKey) throws IOException {
        InputStream inputStream = getContext().getAssets().open("consultation.json");
        // 将 InputStream 转换为 JSON 字符串
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        // 解析 JSON 字符串为 JSONObject
        List<Item> items = UtilsKt.toList(stringBuilder.toString(), Item.class);
        List<Item> realItems = new ArrayList<>();
        for (Item item : items) {
            if (searchKey.equals("") || item.getTitle().contains(searchKey) ) {
                realItems.add(item);
            }
        }
        return realItems;
    }

    class MAdapter extends RecyclerView.Adapter<VH> {

        private List<Item> items;

        public MAdapter(List<Item> items) {
            this.items = items;
        }

        public void updateData(List<Item> items) {
            this.items = items;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_consultation, null);
            return new VH(view);
        }

        @Override
        public void onBindViewHolder(@NonNull VH holder, int position) {
            holder.bind(items.get(position), position);
        }

        @Override
        public int getItemCount() {
            return items.size();
        }
    }

    class VH extends RecyclerView.ViewHolder {

        private View space;
        private TextView title;
        private TextView content;

        public VH(@NonNull View itemView) {
            super(itemView);
            space = itemView.findViewById(R.id.space);
            title = itemView.findViewById(R.id.title);
            content = itemView.findViewById(R.id.content);
        }

        public void bind(Item item, int pos) {
            if (pos == 0) {
                UtilsKt.gone(space);
            } else {
                UtilsKt.visible(space);
            }
            title.setText(item.getTitle());
            content.setText(item.getContent());
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), ConsultationDetailActivity.class);
                    intent.putExtra(ConsultationDetailActivity.KEY_TITLE, item.getTitle());
                    intent.putExtra(ConsultationDetailActivity.KEY_CONTENT, item.getContent());
                    startActivity(intent);
                }
            });
        }
    }

}
